/*
 *    Copyright 2022 jacky4631 shen ji email:121659050@qq.com
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dataoke.shoppingguide.app773026.activity.home;

import static android.widget.Toast.LENGTH_LONG;
import static com.dataoke.shoppingguide.app773026.bean.Constants.DA_TAO_KE_PARSE_CONTENT_URL;
import static com.dataoke.shoppingguide.app773026.bean.Constants.STOP_SPLASH;

import android.Manifest;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;

import com.alibaba.fastjson.JSON;
import com.dataoke.shoppingguide.app773026.AppConfig;
import com.dataoke.shoppingguide.app773026.AppContext;
import com.dataoke.shoppingguide.app773026.JKJApplication;
import com.dataoke.shoppingguide.app773026.R;
import com.dataoke.shoppingguide.app773026.activity.PrivacyManage;
import com.dataoke.shoppingguide.app773026.activity.home.fragment.NavFragment;
import com.dataoke.shoppingguide.app773026.activity.home.fragment.ParseTaoWordDialogFragment;
import com.dataoke.shoppingguide.app773026.activity.update.CheckUpdateManager;
import com.dataoke.shoppingguide.app773026.activity.update.DownloadService;
import com.dataoke.shoppingguide.app773026.base.activities.BaseActivity;
import com.dataoke.shoppingguide.app773026.bean.DataokeParseContent;
import com.dataoke.shoppingguide.app773026.bean.Version;
import com.dataoke.shoppingguide.app773026.util.HttpTools;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupAnimation;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
/**
 *
 * @author: shen ji
 * @date: 2022/3/15
 * @email: 121659050@qq.com
 * @wechat: jacky4631
 */
public class MainActivity extends BaseActivity implements
        EasyPermissions.PermissionCallbacks, CheckUpdateManager.RequestPermissions {

    public static boolean IS_SHOW = false;
    private static final int RC_EXTERNAL_STORAGE = 0x04;//存储权限
    private long mBackPressedTime;
    private ParseTaoWordDialogFragment aboutDialog;
    private Handler splashHandler = new Handler(Looper.myLooper()) {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case STOP_SPLASH:
                    break;
                default:
                    break;
            }

            super.handleMessage(msg);
        }
    };
    private Handler clipHandler = new Handler(Looper.myLooper());

    private Version mVersion;

    private NavFragment mNavBar;
    private List<TurnBackListener> mTurnBackListeners = new ArrayList<>();


    public static void show(Context context) {
        context.startActivity(new Intent(context, MainActivity.class));
    }

    public interface TurnBackListener {
        boolean onTurnBack();
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_main_ui;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        setSwipeBackEnable(false);
        setStatusBarDarkMode();
        FragmentManager manager = getSupportFragmentManager();
        mNavBar = ((NavFragment) manager.findFragmentById(R.id.fag_nav));
        mNavBar.setup(this, manager, R.id.main_container);
        PrivacyManage.checkShow(this, splashHandler);

    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        clipHandler.postDelayed(() -> parseContent(), 1000);
    }

    @Override
    protected void onStart() {
        super.onStart();
        IS_SHOW = true;

        JKJApplication.getContext().setOnVisibilityChangeListener(isAppInBackground -> {
            if (isAppInBackground) {
                clipHandler.postDelayed(() -> parseContent(), 1000);

            }
        });
    }

    protected void parseContent(){
        if(!PrivacyManage.applyPrivacy() || !IS_SHOW) {
            return;
        }
        ClipboardManager mClipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
        if(mClipboardManager == null) {
            return;
        }
        String text;
        if(TextUtils.isEmpty(mClipboardManager.getText())) {
            if(mClipboardManager.hasPrimaryClip() && mClipboardManager.getPrimaryClip().getItemAt(0).getText() != null) {
                text = mClipboardManager.getPrimaryClip().getItemAt(0).getText().toString();
            }else {
                text = null;
            }
        } else {
            text = mClipboardManager.getText().toString();
        }
        if(!TextUtils.isEmpty(text)) {
            HttpTools.get(String.format(DA_TAO_KE_PARSE_CONTENT_URL, text), new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Log.e("MainActivity", String.format(DA_TAO_KE_PARSE_CONTENT_URL, text) + e.getMessage());
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    try {
                        DataokeParseContent parseContent = JSON.parseObject(response.body().string(), DataokeParseContent.class);
                        if(parseContent != null && parseContent.getCode() == 0 && parseContent.getData() != null && !TextUtils.isEmpty(parseContent.getData().getGoodsId())) {
                            if(aboutDialog != null) {
                                aboutDialog.dismiss();
                                aboutDialog = null;
                            }
                            aboutDialog = new ParseTaoWordDialogFragment();
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("content", parseContent.getData());
                            aboutDialog.setArguments(bundle);

                            aboutDialog.show(getSupportFragmentManager(), "ParseTaoWordDialogFragment");
                            clearClipboard();


                        }
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

        }
    }
    /**
     * 清空剪贴板内容
     */
    public void clearClipboard() {
        ClipboardManager manager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
        if (manager != null) {
            try {
                manager.setPrimaryClip(manager.getPrimaryClip());
                manager.setText(null);
            } catch (Exception e) {
            }
        }
    }
    @Override
    protected void initData() {
        super.initData();
        // in this we can checkShare update
//        checkUpdate();

    }

    @Override
    public void call(Version version) {
        this.mVersion = version;
        requestExternalStorage();
    }

    @AfterPermissionGranted(RC_EXTERNAL_STORAGE)
    public void requestExternalStorage() {
        if (EasyPermissions.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            DownloadService.startService(this, mVersion.getDownloadUrl());
        } else {
            EasyPermissions.requestPermissions(this, "", RC_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if(requestCode == 1) {
            Toast.makeText(this, "开启成功，请重新长按保存到相册", LENGTH_LONG).show();
        }

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

        if(requestCode == 1) {
            new XPopup.Builder(this)
                    .isDestroyOnDismiss(true)
                    .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                    .asConfirm("温馨提示", "需要开启" + getString(R.string.app_name) + "对您手机的存储权限才能保存二维码，是否现在开启",
                            "取消", "去开启",
                            () -> {
                                startActivity(new Intent(Settings.ACTION_APPLICATION_SETTINGS));
                            }, null, false).show();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // 将结果转发给 EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    protected void onResume() {
        // onPause之后便可能调用onSaveInstanceState，因此onresume中也需要置true
        IS_SHOW = true;
        super.onResume();

    }
    @Override
    protected void onStop() {
        // onPause之后便可能调用onSaveInstanceState，因此onresume中也需要置true
        IS_SHOW = false;
        super.onStop();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        for (TurnBackListener l : mTurnBackListeners) {
            if (l.onTurnBack()) return;
        }
        boolean isDoubleClick = JKJApplication.get(AppConfig.KEY_DOUBLE_CLICK_EXIT, true);
        if (isDoubleClick) {
            long curTime = SystemClock.uptimeMillis();
            if ((curTime - mBackPressedTime) < (3 * 1000)) {
                finish();
            } else {
                mBackPressedTime = curTime;
                Toast.makeText(this, R.string.tip_double_click_exit, LENGTH_LONG).show();
            }
        } else {
            finish();
        }
    }

    private void checkUpdate() {
        if (!AppContext.get(AppConfig.KEY_CHECK_UPDATE, true)) {
            return;
        }
        CheckUpdateManager manager = new CheckUpdateManager(this, false);
        manager.setCaller(this);
        manager.checkUpdate(false);
    }

    @Override
    protected boolean isSetStatusBarColor() {
        return false;
    }
}
